package easy;

/**
 * @Description :罗马数字转整数
 * @Author : machong
 * @Date : 2022/4/9 1:56
 * @Version : 1.0
 **/
public class leetCode13_romanToInt {
    public static int romanToInt(String s) {
        //为了在循环中计算s串的最后一位，原字符串变长一位
        s = s.concat("#");
        //保存上一个字符
        char ch = s.charAt(0);
        int result = 0;
        //从字符串第二位开始
        for (int i = 1; i < s.length(); i++) {
            if (ch == 'M'){
                result += 1000;
            }else if (ch == 'D'){
                result += 500;
            }else if (ch == 'C'){
                if (s.charAt(i) == 'D' || s.charAt(i) == 'M'){
                    result -= 100;
                }else {
                    result += 100;
                }
            }else if (ch == 'L'){
                result += 50;
            }else if (ch == 'X'){
                if (s.charAt(i) == 'L' || s.charAt(i) == 'C'){
                    result -= 10;
                }else {
                    result += 10;
                }
            }else if (ch == 'V'){
                result += 5;
            }else if (ch == 'I'){
                if (s.charAt(i) == 'V' || s.charAt(i) == 'X'){
                    result -= 1;
                }else {
                    result += 1;
                }
            }
            ch = s.charAt(i);
        }
        return result;
    }
}
